package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.DrilldownSeries;
import com.itheima.reggie.dto.SetmealDiagram;
import com.itheima.reggie.dto.SunBurstChild;
import com.itheima.reggie.dto.SunBurstParent;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.*;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息为：{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功！");
    }


    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //创建分页构造器
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //创建条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //模糊匹配
        lqw.like(null != name, Setmeal::getName, name);
        //根据修改时间进行降序排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        setmealService.page(setmealPage, lqw);
        //对象拷贝，records不需要拷贝
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        //获取records集合的内容
        List<Setmeal> records = setmealPage.getRecords();
        //通过stream遍历集合
        List<SetmealDto> list = records.stream().map((item) -> {
            //创建setmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //根据分类id获取分类对象
            Category category = categoryService.getById(categoryId);
            //判读分类对象是否为空
            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);

        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        setmealService.deleteWithDish(ids);
        return R.success("删除套餐成功！");
    }


    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.updateWithDish(setmealDto);
        return R.success("套餐信息修改成功！");
    }

    /**
     * 停售和起售
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("status:{},ids:{}", status, ids);

        //添加查询操作
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null, Setmeal::getId, ids);
        //添加status是否相等
        lqw.eq(status != null, Setmeal::getStatus, status);

        //根据lqw中的条件查询数据出现的数量
        int count = setmealService.count(lqw);
        //如果数量大于0，说明存在status一样的，则抛出一个业务异常
        if (count > 0) {
            //抛出的异常
            throw new CustomException("请不要进行这种傻逼操作");
        }

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(ids != null, Setmeal::getId, ids);

        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);

        setmealService.update(setmeal, qw);

        return R.success("套餐状态已经更改成功");
    }


    /**
     * 移动端查看套餐详情
     *
     * @param id
     * @return
     */
    @Cacheable(value = "setmealCache", key = "'setmeal' + '_' + #id", unless = "#result == null")
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dish(@PathVariable Long id) {
        log.info("id为：{}", id);
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(lqw);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            dishDto.setCopies(item.getCopies());
            Long dishId = item.getDishId();
            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
            qw.eq(dishId != null, Dish::getId, dishId);
            Dish dish = dishService.getOne(qw);

            BeanUtils.copyProperties(dish, dishDto);

            return dishDto;

        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }


    /**
     * 根据条件查询套餐信息
     *
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status", unless = "#result == null")
    @GetMapping("/list")
    public R<List<SetmealDto>> list(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(lqw);
        List<SetmealDto> setmealDtoList = list.stream().map(item -> {
            Integer saleNum = setmealService.countSaleNum(item.getId(), null, null);
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            setmealDto.setSaleNum(saleNum);
            return setmealDto;
        }).collect(Collectors.toList());
        return R.success(setmealDtoList);
    }


    /**
     * 管理端
     * 套餐销量数据
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @Cacheable(value = "orderCache", key = "'setmealSaleNum_' + #beginTime + '_' + #endTime", unless = "#result == null")
    @GetMapping("/setmealSaleNum")
    public R<List<SetmealDiagram>> setmealSaleNum(String beginTime, String endTime) {

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 查询套餐分类
        queryWrapper.eq(Category::getType, 2);
        List<Category> categoryList = categoryService.list(queryWrapper);

        List<SetmealDiagram> setmealDiagramList = categoryList.stream().map(item -> {
            // 根据分类id查询套餐
            LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, item.getId());
            List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);

            SetmealDiagram setmealDiagram = new SetmealDiagram();
            setmealDiagram.setY(0);
            // 查询该分类id下的所有套餐的月销量
            Object[] array = setmealList.stream().map(setmeal -> {
                Integer num = setmealService.countSaleNum(setmeal.getId(), beginTime, endTime);
                // 将月销量进行相加，得到该分类的月销量
                setmealDiagram.setY(setmealDiagram.getY() + num);
                // 将套餐名称和销量封装为一个数组
                return new Object[]{setmeal.getName(), num};
                // 获得一个二维数组
            }).toArray();
            // 设置分类名
            setmealDiagram.setName(item.getName());
            // 设置分类名
            setmealDiagram.setDrilldown(item.getName());

            DrilldownSeries drilldownSeries = new DrilldownSeries();
            // 设置分类名
            drilldownSeries.setId(item.getName());
            // 设置分类名
            drilldownSeries.setName(item.getName());
            // 设置分类下的套餐销量数据
            drilldownSeries.setData(array);

            setmealDiagram.setDrilldownSeries(drilldownSeries);
            return setmealDiagram;
        }).collect(Collectors.toList());
        return R.success(setmealDiagramList);
    }


    /**
     * 管理端
     * 套餐销量数据
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @Cacheable(value = "orderCache", key = "'setmealSaleNumSun_' + #beginTime + '_' + #endTime", unless = "#result == null")
    @GetMapping("/setmealSaleNumSun")
    public R<SunBurstParent[]> setmealSaleNumSun(String beginTime, String endTime) {
        List<SunBurstParent> sunBurstList = new LinkedList<>();

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 查询套餐分类
        queryWrapper.eq(Category::getType, 2);
        List<Category> categoryList = categoryService.list(queryWrapper);
        String one = "1.";
        String two = "2.";
        int id = 1;
        String oneParent = "0.0";
        SunBurstParent root = new SunBurstParent();
        root.setId(oneParent);
        root.setName("套餐");
        root.setParent("");
        // 将跟数据添加到集合中
        sunBurstList.add(root);
        for (int i = 0; i < categoryList.size(); i++) {
            // 获取分类对象
            Category category = categoryList.get(i);

            // 创建数据对象
            SunBurstParent sunBurstOne = new SunBurstParent();
            // 创建二级数据的父id(即一级数据的id)
            String twoParent = one + (i + 1);
            sunBurstOne.setId(twoParent);
            sunBurstOne.setParent(oneParent);
            sunBurstOne.setName(category.getName());
            // 将一级数据（分类）添加到集合中
            sunBurstList.add(sunBurstOne);

            // 根据分类id查询套餐
            LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, category.getId());
            List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);
            for (Setmeal setmeal : setmealList) {
                SunBurstChild sunBurstTwo = new SunBurstChild();
                sunBurstTwo.setId(two + id++);
                sunBurstTwo.setParent(twoParent);
                sunBurstTwo.setName(setmeal.getName());
                Integer num = setmealService.countSaleNum(setmeal.getId(), beginTime, endTime);
                sunBurstTwo.setValue(num);
                // 将二级数据（套餐）添加到集合中
                sunBurstList.add(sunBurstTwo);
            }
        }
        SunBurstParent[] sunBurstArr = sunBurstList.toArray(new SunBurstParent[sunBurstList.size()]);
        return R.success(sunBurstArr);
    }
}